var todoItem = [];
// localStorage.clear();
window.onload = function () {
  /* // 通过id获取dom节点对象
  var todoBtn = document.getElementById('todo');
  // 打印对象
  console.dir(todoBtn); */
  getTodoList();
  var ok = document.getElementById('ok');
  ok.onclick = function () {
    event.preventDefault();
    window.event.returnValue = false;
    var todoText = document.getElementById('todo').value;
    var date = document.getElementById('date').value;
    var time = document.getElementById('time').value;
    //console.log(todoText, date, time);
    var itemInfo = {
      todoText: todoText,
      date: date,
      time: time,
      state: '0'
    } 
    console.log(todoItem);
    todoItem.push(itemInfo);
    localStorage.setItem('todoItems', JSON.stringify(todoItem));
    //localStorage.clear();
    //console.log(todoItem);
    //console.log(localStorage);
    location.reload();
  }
  //console.log(localStorage);
  function getTodoList () {
    todoItem = localStorage.getItem('todoItems');
    if (!todoItem || (todoItem === '[]')) {
      todoItem = [];
    } else {
      todoItem = JSON.parse(todoItem);
    }
    for (var i = 0; i < todoItem.length; i++) {
      var tr = document.createElement('tr');
      tr.innerHTML = `<td align="center">${i+1}</td>
      <td>${todoItem[i].todoText}</td>
      <td align="center">${todoItem[i].date} ${todoItem[i].time}</td>
      <td align="center">
        <select class="select" onchange="modify(this)">
          <option value="0">未开始</option>
          <option value="1">正在进行</option>
          <option value="2">已完成</option>
        </select>
      </td>`;
      document.getElementById('todoTable').appendChild(tr);
      var options = document.getElementsByClassName('select')[i].getElementsByTagName('option');
      for (var j = 0; j < options.length; j++) {
        var value = options[j].value;
        if (value === todoItem[i].state) {
          options[j].setAttribute('selected', 'selected');
        }
      }
    }
    console.log(todoItem);
  }
}
function modify (value) {
  console.dir(value);
  var tr = value.parentNode.parentNode;
  var trs = document.getElementById('todoTable').getElementsByTagName('tr');
  for (var i in trs) {
    if (trs[i] == tr) {
      console.log(i);
      todoItem[i - 1].state = value.value;
      console.log(todoItem[i - 1]);
      localStorage.setItem('todoItems', JSON.stringify(todoItem));
    }
  }
}